import 'package:get/get.dart';
import 'package:app_core/app_core.dart';
import 'package:yh_core_flutter_project/project/modules/login/models/user_model/user_model.dart';
import '../utils/storage_util.dart';

final userManager = UserManager.instance;

class UserManager extends GetxController {
  static UserManager get instance => Get.find();

  ///通过Rx 变量赋值来“实时响应，UI层比较需用getx的组件包裹
  final _userModel = Rxn<UserModel>();
  final _token = RxnString();
  final _isFirstLogin = true.obs;

  /// 用户信息
  UserModel? get userModel => _userModel.value;

  /// 用户id
  String? get userId => userModel?.userId;

  /// 用户Token
  String? get token => _token.value;

  /// 是否已登录（基于Token是否存在）
  bool get isLoggedIn => _token.value != null && _token.value!.isNotEmpty;

  /// 是否第一次登录
  bool get isFirstLogin => _isFirstLogin.value;

  @override
  void onInit() {
    super.onInit();
    _restoreState();
  }

  /// 登录成功后调用：保存内存 + 本地存储
  Future<void> loginSave(UserModel model) async {
    _userModel.value = model;
    _token.value = model.token;
    await StorageUtil.setUserToken(model.token ?? '');
    await StorageUtil.setUserInfo(model.toJson());
  }

  /// 登出：清空内存 + 清空存储 + 刷新全局
  Future<void> logout() async {
    _userModel.value = null;
    _token.value = null;
    await StorageUtil.clearUserData();
    Get.forceAppUpdate();
  }

  /// 标记欢迎页完成
  Future<void> markWelcomeCompleted() async {
    _isFirstLogin.value = false;
    await StorageUtil.setIsFirstLogin(false);
  }

  /// 启动恢复：从本地还原登录态
  void _restoreState() {
    try {
      _token.value = StorageUtil.getUserToken();
      _isFirstLogin.value = StorageUtil.getIsFirstLogin();
      final map = StorageUtil.getUserInfo();
      if (map != null) {
        _userModel.value = UserModel.fromJson(map);
      }
      YHLog.d('🔐 登录恢复: isLoggedIn=$isLoggedIn, isFirstLogin=$isFirstLogin, userId=${userModel?.userId}');
    } catch (e) {
      YHLog.e('❌ 登录恢复失败: $e');
    }
  }
}
